package cn.tedu.charging.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 通过Jackson实现Json和对象转换工具
 */
public class JsonUtils {

    private static ObjectMapper mapper = new ObjectMapper();

    /**
     * 将对象转换为Json字符串
     */
    public static String toJson(Object obj) {
     try {
         return mapper.writeValueAsString(obj);
     } catch (JsonProcessingException e) {
         throw new RuntimeException(e);
     }
    }


    /**
     * 将Json字符串转换为对象
     */
    public static <T> T fromJson(String json, Class<T> clazz) {
        try {
            return mapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }


    public static <T> T covertValue(Object object, Class<T> clazz) {
        return mapper.convertValue(object,clazz);
    }


}
